import Flutter
import UIKit
import AVFoundation

public class HeicConverterPlugin: NSObject, FlutterPlugin {
    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "heic_converter", binaryMessenger: registrar.messenger())
        let instance = HeicConverterPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }
    
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        case "convertToJpg":
            guard let arguments = call.arguments as? [String: Any],
                  let imagePath = arguments["path"] as? String else {
                result(FlutterError(code: "INVALID_ARGUMENTS", message: "Invalid arguments", details: nil))
                return
            }
            convertToJpg(from: imagePath, result: result)
        case "convertToPng":
            guard let arguments = call.arguments as? [String: Any],
                  let imagePath = arguments["path"] as? String else {
                result(FlutterError(code: "INVALID_ARGUMENTS", message: "Invalid arguments", details: nil))
                return
            }
            convertToPng(from: imagePath, result: result)
        case "isBluetoothAudioOutput":
            let isBluetooth = isBluetoothAudioOutput()
            result(isBluetooth)
        default:
            result(FlutterMethodNotImplemented)
        }
    }
    
    private func isBluetoothAudioOutput() -> Bool {
        // let audioSession = AVAudioSession.sharedInstance()
        // let currentRoute = audioSession.currentRoute
        // for output in currentRoute.outputs {
        //     if output.portType == .bluetoothA2DP || output.portType == .bluetoothHFP {
        //         return true
        //     }
        // }
        // return false
        let audioSession = AVAudioSession.sharedInstance()
        do {
            try audioSession.setActive(true)
            let currentRoute = audioSession.currentRoute
            for output in currentRoute.outputs {
                if output.portType == .bluetoothA2DP {
                    return true
                }
            }
        } catch {
            print("Error checking audio route: \(error)")
        }
        return false
    }
    
    //   private func convertToJpg(from imagePath: String, result: @escaping FlutterResult) {
    //     guard let image = UIImage(contentsOfFile: imagePath) else {
    //       result(FlutterError(code: "IMAGE_NOT_FOUND", message: "The provided image path does not exist.", details: nil))
    //       return
    //     }
    //     guard let imageData = image.jpegData(compressionQuality: 1.0) else {
    //       result(FlutterError(code: "CONVERSION_FAILED", message: "Failed to convert image to JPG.", details: nil))
    //       return
    //     }
    //     let jpgPath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("converted.jpg").path
    //     do {
    //       try imageData.write(to: URL(fileURLWithPath: jpgPath))
    //       result(jpgPath)
    //     } catch {
    //       result(FlutterError(code: "WRITE_FAILED", message: "Failed to write JPG file.", details: error.localizedDescription))
    //     }
    //   }
    
    //   private func convertToPng(from imagePath: String, result: @escaping FlutterResult) {
    //     guard let image = UIImage(contentsOfFile: imagePath) else {
    //       result(FlutterError(code: "IMAGE_NOT_FOUND", message: "The provided image path does not exist.", details: nil))
    //       return
    //     }
    //     guard let imageData = image.pngData() else {
    //       result(FlutterError(code: "CONVERSION_FAILED", message: "Failed to convert image to PNG.", details: nil))
    //       return
    //     }
    //     let pngPath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("converted.png").path
    //     do {
    //       try imageData.write(to: URL(fileURLWithPath: pngPath))
    //       result(pngPath)
    //     } catch {
    //       result(FlutterError(code: "WRITE_FAILED", message: "Failed to write PNG file.", details: error.localizedDescription))
    //     }
    //   }
    
    private func convertToJpg(from imagePath: String, result: @escaping FlutterResult) {
        guard let image = UIImage(contentsOfFile: imagePath) else {
            result(FlutterError(code: "IMAGE_NOT_FOUND", message: "The provided image path does not exist.", details: nil))
            return
        }
        guard let imageData = image.jpegData(compressionQuality: 1.0) else {
            result(FlutterError(code: "CONVERSION_FAILED", message: "Failed to convert image to JPG.", details: nil))
            return
        }
        
        let fileURL = URL(fileURLWithPath: imagePath)
        let fileName = fileURL.deletingPathExtension().lastPathComponent + ".jpg"
        let jpgPath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName).path
        
        do {
            try imageData.write(to: URL(fileURLWithPath: jpgPath))
            result(jpgPath)
        } catch {
            result(FlutterError(code: "WRITE_FAILED", message: "Failed to write JPG file.", details: error.localizedDescription))
        }
    }
    
    private func convertToPng(from imagePath: String, result: @escaping FlutterResult) {
        guard let image = UIImage(contentsOfFile: imagePath) else {
            result(FlutterError(code: "IMAGE_NOT_FOUND", message: "The provided image path does not exist.", details: nil))
            return
        }
        guard let imageData = image.pngData() else {
            result(FlutterError(code: "CONVERSION_FAILED", message: "Failed to convert image to PNG.", details: nil))
            return
        }
        
        let fileURL = URL(fileURLWithPath: imagePath)
        let fileName = fileURL.deletingPathExtension().lastPathComponent + ".png"
        let pngPath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName).path
        
        do {
            try imageData.write(to: URL(fileURLWithPath: pngPath))
            result(pngPath)
        } catch {
            result(FlutterError(code: "WRITE_FAILED", message: "Failed to write PNG file.", details: error.localizedDescription))
        }
    }
}
